/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 巴枪扫描记录
 *  */
import React, { useState, useCallback, useMemo, useEffect } from 'react';
import StandardTab from '@/components/StandardTab';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { message, Row, Col, Button } from 'antd';
import { connect } from 'dva';
import { setLStorage, getLStorage } from '@/utils/utils';
import AddressCascader from '@/components/AddressCascader';
import Exception from '@/components/Exception';
import DispatchPianqu from '@/components/_pages/Post/Area/DispatchPianqu';
import GunScanRecordTemplate from './components/GunScanRecordTemplate';
import styles from './style.less';

const GunScanRecord = ({ userInfo = {}, options = {}, dispatch, is_gp }) => {
  const {
    branch = [],
    shop_id,
    branchId,
    branchLevel,
    phone,
    gp_area_ids = [],
    area_ids,
  } = userInfo;
  const isCompany = area_ids == '*';
  const { key, topAccountTitle } = options;
  const isYjy = key === 'yjy';
  const isZyAccount = key == 'post' || isYjy;
  const isTopAccount = isZyAccount && branch.length === 0;
  const isCountry = isZyAccount && branchLevel == 3;
  // 中邮地址id
  const addressId = isZyAccount
    ? getLStorage(shop_id) ||
      (isTopAccount ? [] : branch.filter(val => val.level != 0).map(i => i.id))
    : [];
  // 中邮地址下拉数据
  const addressOption = getLStorage(`${shop_id}_addressOptions`) || [];
  // 中邮当前账号的所属区域
  const currentBranch = useMemo(() => (isTopAccount ? [] : branch.filter(val => val.level != 0)), [
    branch,
    isTopAccount,
  ]);
  const initTabKey = isZyAccount && !isYjy ? 'arrive' : 'send';

  const [activeKey, setActiveKey] = useState(initTabKey);
  const [addressIds, setAddressId] = useState(addressId);
  const [addressOptions, setAddressOptions] = useState(addressOption);

  // 获取所有的网点信息
  const getBranchInfo = useCallback(
    ({ waybill_type, branch_id, area_id }) => {
      dispatch({
        type: 'allocation/getBranchInfo',
        payload: {
          brand: 'all',
          waybill_type,
          branch_id,
          area_id,
        },
      });
    },
    [dispatch],
  );

  const onChange = useCallback(
    _activeKey => {
      setLStorage(`${shop_id}_gunScanRecordTabKey`, _activeKey);
      setActiveKey(_activeKey);
      if (!isZyAccount) {
        const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
        const reqAreaId = gp_area_ids.includes(cacheAreaId)
          ? cacheAreaId
          : isCompany
            ? '0'
            : gp_area_ids[0];
        getBranchInfo({
          waybill_type: _activeKey,
          area_id: reqAreaId,
        });
      }
    },
    [shop_id, gp_area_ids, isZyAccount],
  );

  const onAddressSelect = useCallback(
    (value, _, option) => {
      const address_options = option[0] ? option : addressOptions;
      setAddressId(value);
      setAddressOptions(address_options);
    },
    [addressOptions],
  );

  const onSwitchAddress = useCallback(
    () => {
      if (addressIds.length >= 3) {
        message.success('切换成功！');
        setLStorage(shop_id, addressIds);
        setLStorage(`${shop_id}_addressOptions`, addressOptions);
        dispatch({
          type: 'allocation/save',
          payload: {
            addressId: addressIds,
          },
        });
        // 切换地区时，更新网点编号
        getBranchInfo({ waybill_type: activeKey, branch_id: addressIds[2] });
      } else {
        message.warn('请选择具体区域');
      }
    },
    [addressIds, addressOptions, dispatch, shop_id, activeKey, getBranchInfo],
  );

  const ExtraContent = useMemo(
    () => () => (
      <Row type="flex" gutter={[10, 0]} align="middle">
        <Col>
          <span>县级区域：</span>
        </Col>
        <Col>
          <AddressCascader
            canChooseParent={false}
            type="cache"
            level={3}
            placeholder="请选择具体县级区域"
            width={300}
            request
            companyId={branchId}
            branch={currentBranch}
            value={addressIds}
            onSelect={onAddressSelect}
            optionsFromProps={addressOptions}
          />
        </Col>
        <Col>
          <Button type="primary" onClick={onSwitchAddress}>
            切换
          </Button>
        </Col>
      </Row>
    ),
    [addressIds, addressOptions, branchId, currentBranch, onAddressSelect, onSwitchAddress],
  );

  const panes = useMemo(
    () => {
      const components = [
        {
          tab: '发件',
          key: 'send',
          component: <GunScanRecordTemplate type="send" addressId={addressIds} />,
        },
        {
          tab: '到件',
          key: 'arrive',
          component: <GunScanRecordTemplate type="arrive" addressId={addressIds} />,
        },
        {
          tab: '派件',
          key: 'delivery',
          component: <GunScanRecordTemplate type="delivery" addressId={addressIds} />,
        },
        {
          tab: '签收件',
          key: 'sign',
          component: <GunScanRecordTemplate type="sign" addressId={addressIds} />,
        },
        {
          tab: '问题件',
          key: 'error',
          component: <GunScanRecordTemplate type="error" addressId={addressIds} />,
        },
      ];
      if (isZyAccount && !isYjy) {
        components.splice(0, 1);
        components.splice(-1, 1);
      }
      return components;
    },
    [isZyAccount, addressIds, isYjy],
  );

  const onChangePianqu = area_id => {
    getBranchInfo({
      waybill_type: activeKey,
      area_id,
    });
  };

  useEffect(
    () => {
      const { hash } = location;
      if (!hash) {
        // 首次进入的时候，跳转到最后一次选中的tab页
        const tabKey = getLStorage(`${shop_id}_gunScanRecordTabKey`) || initTabKey;
        setActiveKey(tabKey);
      }
      // 判断区县一级是否开通共配
      if (isCountry) {
        dispatch({
          type: 'allocation/getUserInfo',
        });
      }
    },
    [dispatch, isCountry, shop_id, initTabKey],
  );

  if (is_gp == 0 && isCountry) {
    // 当县级网点无共配权限时，提示
    return (
      <Exception
        type="403"
        title={`您所在的网点尚未开通共配服务，请联系${topAccountTitle}开通！`}
      />
    );
  }

  return (
    <PageHeaderLayout
      title={
        <Row type="flex" justify="space-between" align="middle">
          <Col>巴枪扫描记录</Col>
          <Col>
            {isZyAccount ? (
              <ExtraContent />
            ) : (
              <DispatchPianqu type="gp" onChange={onChangePianqu} />
            )}
          </Col>
        </Row>
      }
    >
      <div className={styles.main}>
        <div style={{ paddingBottom: '24px' }}>
          <StandardTab
            style={{ marginBottom: 24 }}
            onChange={onChange}
            activeKey={activeKey}
            name="gunScanRecord"
            panes={panes}
          />
        </div>
      </div>
    </PageHeaderLayout>
  );
};

export default connect(({ setting, user, allocation }) => ({
  options: setting.options,
  userInfo: user.currentUser.user_info,
  is_gp: allocation.deductionInfo.is_gp,
}))(React.memo(GunScanRecord));
